package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFAnchor;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    WorkspaceService workspaceService;



    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {

        //当前集合用于存放begin到end的日期
        List<LocalDate> datelist = new ArrayList<>();
        datelist.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            datelist.add(begin);
        }

        List<Double> turnoverList = new ArrayList<>();
        //遍历集合来查看当天的订单数量
        for (LocalDate date : datelist) {
            //查询对应日期的订单金额,订单是已完成的订单数量
            LocalDateTime begintime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(date, LocalTime.MAX);
            //select sum(amount) form orders where status = 5 and order_time > begintime and order_time < endtime
            Map map = new HashMap();
            map.put("being", begintime);
            map.put("end", endtime);
            map.put("status", Orders.COMPLETED);
            Double sum = orderMapper.sumByMap(map);
            sum = sum == null ? 0.0 : sum;
            turnoverList.add(sum);
        }

        //封装
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(datelist, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();

    }

    /**
     * 用户信息统计
     *
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {

        //当前集合用于存放日期
        List<LocalDate> localDates = new ArrayList<>();
        localDates.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            localDates.add(begin);
        }

        //用户总量
        //存放用户新增数量集合
        List<Integer> userlist = new ArrayList<>();
        //存放用户总数量的集合
        List<Integer> userslist = new ArrayList<>();
        //循环取出日期内的用户量
        for (LocalDate date : localDates) {
            LocalDateTime begintime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(date, LocalTime.MAX);
            //查询新增用户的数量
            //select count(id) form user where create_time>begin and create_time<end
            Map map = new HashMap();
            map.put("end", endtime);
            Integer countId = userMapper.countByMap(map);
            countId = countId == null ? 0 : countId;
            userlist.add(countId);
            //查询当前的用户总数量
            //select count(id) form user where create_time<end
            Map maps = new HashMap();
            maps.put("begin", begintime);
            maps.put("end", endtime);
            Integer countsId = userMapper.countByMap(maps);
            countsId = countsId == null ? 0 :countsId;
            userslist.add(countsId);
        }

        //封装
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(localDates,","))
                .totalUserList(StringUtils.join(userslist,","))
                .newUserList(StringUtils.join(userlist,","))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {

        //当前集合用于存放日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //存放每天订单数集合
        List<Integer> orderCountList = new ArrayList<>();
        //存放每天有效订单数集合
        List<Integer> vaildOrderCountList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime begintime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(date, LocalTime.MAX);
            //查询每天订单数量
            //select count(id) from order where order_tiem>begintime and order_time<endtime
            Integer orderCount =getOrderCount(begintime,endtime,null);
            orderCountList.add(orderCount);
            //查询每天有效订单数量
            //select count(id) from order where order_tiem>begintime and order_time<endtime and status=5
            Integer validOrderCount = getOrderCount(begintime,endtime,Orders.COMPLETED);
            vaildOrderCountList.add(validOrderCount);
        }
        //订单总数
        Integer totalorderCount = orderCountList.stream().reduce(Integer::sum).get();
        //有效订单数
        //select count(id) from order where order_time<endtime and status=5
        Integer totalVaildOrderCount = vaildOrderCountList.stream().reduce(Integer::sum).get();
        //订单完成率
        //订单有效数/订单总数
        Double orderCompletionRate = totalorderCount != 0 ? totalorderCount.doubleValue()/totalVaildOrderCount:0;

        //封装
        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(vaildOrderCountList,","))
                .validOrderCount(totalVaildOrderCount)
                .totalOrderCount(totalorderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

    }
    private Integer getOrderCount(LocalDateTime being,LocalDateTime end,Integer status){
        Map map = new HashMap<>();
            map.put("begin",being);
            map.put("end",end);
            map.put("status",status);
        return orderMapper.countByMap(map);
    }


    /**
     * 销量前十统计
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getSalesTop10Statistics(LocalDate begin, LocalDate end) {

        LocalDateTime begintime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endtime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> list = orderMapper.getSalesTop(begintime,endtime);

        List<String> names = list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String name = StringUtils.join(names, ",");

        List<Integer> numbers = list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String number = StringUtils.join(numbers, ",");


        return SalesTop10ReportVO
                .builder()
                .nameList(name)
                .numberList(number)
                .build();

    }


    /**
     * 导出运营数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {

        //查询数据库,查出运营数据
        LocalDate datebegin = LocalDate.now().minusDays(30);
        LocalDate dateend = LocalDate.now().minusDays(1);

        LocalDateTime begin = LocalDateTime.of(datebegin, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(dateend, LocalTime.MAX);

        //查询到的概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(begin, end);
        //通过POI将数据导入到excel中
        //获取模拟流信息
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于已有的文件创建一个新的excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //获取标签页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充数据
            sheet.getRow(1).getCell(1).setCellValue("时间:"+datebegin+"至"+dateend);
            //获取第四行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            //获取第五行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            for (int i = 0; i < 30; i++) {
                //循环找出每天的订单
                LocalDate localDate = datebegin.plusDays(i);
                begin = LocalDateTime.of(localDate, LocalTime.MIN);
                end = LocalDateTime.of(localDate, LocalTime.MAX);
                businessDataVO = workspaceService.getBusinessData(begin,end);
                row = sheet.getRow(7+i);
                row.getCell(1).setCellValue(localDate.toString());
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            }

            //通过输出流将excel文件下载到客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            //关闭资源
            excel.close();

        } catch (IOException e) {
            e.printStackTrace();

        }



    }
}
